package com.cby.operation.login.js

import android.content.Context
import android.text.TextUtils
import android.webkit.JavascriptInterface
import com.cby.operation.common.ui.UIStackManager
import com.cby.operation.common.util.CbyLogUtils
import com.cby.operation.login.LoginManager
import com.cby.operation.sdk.CODE_LOGIN_CANCEL
import com.cby.operation.sdk.CODE_LOGIN_SUCCESS
import com.cby.operation.sdk.MSG_LOGIN_CANCEL
import com.cby.operation.sdk.TAG_FRAGMENT_LOGIN_WEB
import com.cby.operation.sdk.js.BaseJsInterface
import org.json.JSONException
import org.json.JSONObject

/**
 * @description: LoginJsInterface
 *
 * @author ChenBaoyang
 * @date 7/23/21 14:14
 */
class LoginJsInterface(private val context: Context) : BaseJsInterface(context) {

    companion object{
        const val KEY_USER_ID = "userId"
        const val KEY_NICK = "nick"
        const val KEY_TOKEN = "token"
        const val KEY_LOGIN_TYPE = "loginType"
    }

    /**
     * h5登录结果回调
     *
     * @param json
     */
    @JavascriptInterface
    fun onLoginCallback(json: String, code: Int, msg: String) {
        CbyLogUtils.flog(
            "code= " + code + "json=" + json + "====msg==" + msg
        )
        loginCallBack(json, code, msg)
    }

    private fun loginCallBack(json: String?, code: Int, msg: String?) {
        if (code == CODE_LOGIN_SUCCESS) {
            if (!TextUtils.isEmpty(json)) {
                try {
                    val jsonObject = JSONObject(json)
                    val userId = jsonObject.getString(KEY_USER_ID)
                    val nick = jsonObject.getString(KEY_NICK)
                    val token = jsonObject.getString(KEY_TOKEN)
                    val loginType = jsonObject.getString(KEY_LOGIN_TYPE)
                    UIStackManager.instance!!.finishFragment(TAG_FRAGMENT_LOGIN_WEB)
                    LoginManager.instance.createInternalUser(userId, nick, loginType, token)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        } else {
            LoginManager.instance.handleFailedCallback(code, msg)
        }
    }

    @JavascriptInterface
    fun onLoginClose() {
        CbyLogUtils.flog("onLoginClose")
        UIStackManager.instance!!.finishFragment(TAG_FRAGMENT_LOGIN_WEB)
        LoginManager.instance.handleFailedCallback(CODE_LOGIN_CANCEL, MSG_LOGIN_CANCEL)
    }


}